/*
 * @Author: 李家磊
 * @Date: 2022-03-15 16:49:14
 * @LastEditTime: 2022-03-24 15:58:35
 * @LastEditors: 李家磊
 * @Description:
 * @FilePath: /CURD/src/pages/first/index.tsx
 */
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Form, Input, message, Modal, Popconfirm, Space, Table } from 'antd';
import React, { useEffect, useState } from 'react';

import styles from '@/pages/CommonLess/List.less';
import formStyles from '@/pages/CommonLess/Form.less';
import { addUsers, deleteUsers, queryUsers, updateUsers } from '@/services/Users';

interface pageProps {
  actionTable: string;
}

const page: React.FC<pageProps> = (props) => {
  const { actionTable } = props;

  const search = React.useRef<any>();
  const [isVisible, setIsVisible] = useState<boolean>(false);
  const [isUpdate, setIsUpdate] = useState<boolean>(true);
  const [row, setRow] = useState<API.Users>({});
  const [data, setData] = useState<API.Users[]>([]);

  useEffect(() => {
    let isUnmount = false;
    const getApps = async () => {
      let result = await queryUsers();
      if (result && result.data && !isUnmount) {
        setData(result.data.data);
      }
    };
    getApps();
    return () => {
      isUnmount = true;
    };
  }, [actionTable]);

  const refreshTable = async(params?: any) => {
    let result = await queryUsers(params);
    if (result && result.data.data){
      setData(result.data.data);
    }
  }

  const searchSubmit = async () => {
    if(search.current){
      let result = await queryUsers({searchContent: search.current.state.value})
      if(result && result.status === 1){
        await refreshTable({searchContent: search.current.state.value})
      }else{
        message.error("请输入正确的关键词")
      }
    }
  };

  const onFinish = async (value: any) => {
    let result = await addUsers(value);
    if(result && result.status === 1){
      setIsVisible(false);
      await refreshTable();
      message.success("添加成功")
      setRow({});
    }else{
      message.error("添加失败")
    }
  };

  const onUpdate = async (value: any) => {
    let result = await updateUsers(value);
    if(result && result.status === 1){
      setIsVisible(false);
      await refreshTable();
      message.success("修改成功")
      setRow({});
    }else{
      message.error("修改失败")
    }
  }

  const onCancel = () => {
    setRow({});
    setIsVisible(false);
  };

  const deleteData = async (record: API.Users) => {
    let result = await deleteUsers(record)
    if(result && result.data.result){
      message.success("删除成功")
      await refreshTable()
    }else{
      message.error("删除失败")
    }
  }

  const columns = [
    {
      title: '编号',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '年龄',
      dataIndex: 'age',
      key: 'age',
    },
    {
      title: '联系方式',
      dataIndex: 'tel',
      key: 'tel',
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 100,
      render: (text: any, record: any, index: number) => (
        <Space>
          <a
            onClick={() => {
              setIsUpdate(true);
              setIsVisible(true);
              setRow(record);
            }}
          >
            编辑
          </a>
          <Popconfirm
            title="是否删除?"
            onConfirm={()=>{
              deleteData(record)
            }}
            onCancel={() => {}}
            okText="删除"
            cancelText="取消"
          >
            <a>删除</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];
  return (
    <PageContainer>
      <div className={styles.header}>
        <Space>
          <div>关键字</div>
          <Input
            maxLength={20}
            ref={search}
            onPressEnter={searchSubmit}
            allowClear
            placeholder="姓名/年龄/联系方式"
          />
          <Button type="primary" onClick={searchSubmit}>
            搜索
          </Button>
        </Space>
        <Space>
          <Button
            type="primary"
            onClick={() => {
              setIsVisible(true);
              setIsUpdate(false);
            }}
          >
            新建
          </Button>
        </Space>
      </div>
      <div>
        <Table
          bordered
          dataSource={data}
          columns={columns}
        />
      </div>
      <Modal
        visible={isVisible}
        maskClosable={false}
        title={isUpdate ? '编辑数据' : '新建数据'}
        destroyOnClose
        // onOk={finish}
        onCancel={() => {
          onCancel();
        }}
        footer={null}
      >
        <Form
          className={formStyles.Form}
          {...{
            labelCol: { span: 5 },
            wrapperCol: { span: 19 },
          }}
          onFinish={isUpdate ? onUpdate : onFinish }
        >
          <Form.Item label="编号" name="id" initialValue={row.id}>
            <Input disabled={isUpdate} />
          </Form.Item>
          <Form.Item label="姓名" name="name" initialValue={row.name}>
            <Input />
          </Form.Item>
          <Form.Item label="年龄" name="age" initialValue={row.age}>
            <Input />
          </Form.Item>
          <Form.Item label="联系方式" name="tel" initialValue={row.tel}>
            <Input />
          </Form.Item>
          <Space className={formStyles.Space}>
            <Button
              type="primary"
              onClick={() => {
                onCancel();
              }}
            >
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              {isUpdate ? '更改' : '保存'}
            </Button>
          </Space>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default page;
